import { ref, computed, reactive, h } from "vue";
import { defineStore } from "pinia";

export const useMenuStore = defineStore(
  "menu",
  () => {
    const collapsed = ref<boolean>(false);
    const selectedKeys = ref<any>([]);
    const openKeys = ref<string[]>([]);
    const menuList = reactive([]);

    function setSelectedKeys(url: string) {
      selectedKeys.value = [];
      let parent: any[] = [];
      function findMenu(list: any, url: string, index: number) {
        for (let m of list) {

          parent[index] = m;
          for(let i = parent.length - 1; i >= 0; i--){
            if(i > index){
              parent.splice(i, 1)
            }
          }

          if (m.url == url) {
            // 找到了
            selectedKeys.value = [m.key];
            return true
          }
         
          if (m.children) {
            
            let ret = findMenu(m.children, url, index + 1);
            if(ret){
              return true
            }
          }
        }
      }
      let isFind = findMenu(menuList, url, 0);
      if(isFind){
        
        let arr = openKeys.value.concat(parent.map((obj) => obj.key)) ;
        openKeys.value = Array.from(new Set(arr))
      }
      
    }

    return {
      menuList,
      collapsed,
      selectedKeys,
      openKeys,
      setSelectedKeys,
    };
  },
  { persist: false }
);
